package mo_gorm

import (
	consts2 "MoSkeleton/config/consts"
	"golang.org/x/exp/constraints"
	"gorm.io/gorm"
	"strings"
)

/*
从类型gorm中field定义获取gorm的tag

ID        uint `gorm:"primarykey;autoIncrement=false"`
处理primarykey;autoIncrement=false 部
*/
func GetGormTagValByName(tagStr, name string) string {
	if tagStr == "" || name == "" {
		return ""
	}

	upName := strings.ToUpper(name)
	items := strings.Split(tagStr, ";")
	for _, item := range items {
		tag := strings.Split(item, "=")
		if strings.ToUpper(tag[0]) == upName {
			if len(tag) == 2 {
				return tag[1]
			} else {
				return ""
			}
		}
	}
	return ""
}

func GetGormTagMap(tagStr string) map[string]string {
	items := strings.Split(tagStr, ";")
	tagMap := make(map[string]string)
	for _, item := range items {
		tag := strings.Split(item, "=")
		if len(tag) == 2 {
			tagMap[tag[0]] = tag[1]
		} else {
			tagMap[tag[0]] = ""
		}
	}
	return tagMap
}

func GormGet[T constraints.Ordered](db *gorm.DB, key string, defVal T) T {
	return GormGetInterface(db, key, defVal).(T)
}

func GormGetInterface(db *gorm.DB, key string, defVal interface{}) interface{} {
	val, exists := db.Get(key)
	if exists {
		return val
	} else {
		return defVal
	}
}

func GormInstanceGet[T constraints.Ordered](db *gorm.DB, key string, defVal T) T {
	return GormInstanceGetInterface(db, key, defVal).(T)
}
func GormInstanceGetInterface(db *gorm.DB, key string, defVal interface{}) interface{} {
	val, exists := db.InstanceGet(key)
	if exists {
		return val
	} else {
		return defVal
	}
}

func IncDataScopeCount(db *gorm.DB, incCount int) (oldCount int) {
	countIntf, exists := db.Get(consts2.Gorm_Config_DataScope_Count)
	if exists {
		oldCount := countIntf.(int)
		db.Set(consts2.Gorm_Config_DataScope_Count, oldCount+incCount)
	} else {
		oldCount = 0
		db.Set(consts2.Gorm_Config_DataScope_Count, oldCount+incCount)
	}
	return
}

func ResetDataScopeCount(db *gorm.DB) {
	db.Set(consts2.Gorm_Config_DataScope_Count, 0)
}
